package com.example.security.service.impl;

import com.example.security.annotation.DataScope;
import com.example.security.dto.OrgQuery;
import com.example.security.entity.SysOrg;
import com.example.security.mapper.OrgMapper;
import com.example.security.mapper.SysOrgMapper;
import com.example.security.mapper.UserMapper;
import com.example.security.service.OrgService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;

@Service
@RequiredArgsConstructor
@Slf4j
public class OrgServiceImpl implements OrgService {

    private final OrgMapper orgMapper;
    private final UserMapper userMapper;
    private final RedisTemplate<String, Object> redisTemplate;


    @DataScope(orgAlias = "o")
    public List<SysOrg> getOrgList(OrgQuery query) {
        return orgMapper.selectList(query);
    }
    @Override
    public List<Long> getSubOrgIds(Long orgId) {
        String cacheKey = "org:sub:" + orgId;
        List<Long> subIds = (List<Long>) redisTemplate.opsForValue().get(cacheKey);
        if (subIds == null) {
            subIds = orgMapper.selectSubIds(orgId);
            redisTemplate.opsForValue().set(cacheKey, subIds, 1, TimeUnit.HOURS);
        }
        return subIds;
    }

    @Transactional(rollbackFor = Exception.class)
    public void updateOrgUser(Long orgId, List<Long> userIds) {
        try {
            // 更新用户的组织机构
            userMapper.updateOrgId(orgId, userIds);
            // 清除相关缓存
            clearOrgCache(orgId);
        } catch (Exception e) {
            log.error("更新组织机构用户失败", e);
            throw new RuntimeException("更新组织机构用户失败", e);
        }
    }

    /**
     * 清除组织机构相关缓存
     */
    private void clearOrgCache(Long orgId) {
        String subIdsCacheKey = "org:sub:" + orgId;
        redisTemplate.delete(subIdsCacheKey);
    }
} 